import os, types, sys

Plugin_types = ('PRE-PROCESSOR', 'POST-PROCESSOR', 'ENHANCER')
plugin_path = 'plugins'

Plugins = {}
Transdirs = []

def mount_plugins(path = 'plugins'):
    sys.path.insert(0, path)
    modules = []
    module_names = []
    for file in os.listdir(path):
        mn = ''
        if os.path.isfile('%s%s%s' %(path, os.sep, file)):
            if not (file.endswith('.py') \
                or file.endswith('.pyc') \
                or file.endswith('.pyo')) \
                or file.startswith('__init__.py'):
                continue
            else:
                mn = file.split('.py')[0]
        elif os.path.isdir('%s%s%s' %(path, os.sep, file)):
            subfiles = os.listdir('%s%s%s' %(path, os.sep, file))
            if not ('__init__.py' in subfiles \
                or '__init__.pyc' in subfiles \
                or '__init__.pyo' in subfiles):
                continue
            else:
                mn = file
        if mn and not mn in module_names:
            module_names.append(mn)

    for m in module_names:
        #print m
        try:
            modules.append(__import__(m))
        except Exception, e:
            sys.stderr.write('Error: %s; Module: %s' %(e, m))
    sys.path.remove(path)
    return modules

for p in mount_plugins(plugin_path):
    for cls in [p.__dict__.get(a) for a in dir(p)
            if type(p.__dict__.get(a)) == types.ClassType]:
        attrs = dir(cls)
        if 'Transdir' in attrs and cls.Transdir != '' and os.path.isdir(cls.Transdir):
            Transdirs.append(cls.Transdir)
        if 'Type' in attrs and cls.Type in Plugin_types:
            if 'Name' in attrs and cls.Name:
                name = cls.Name
            else:
                name = cls.__name__
            if name:
                plugin_info = {
                        'name': name,
                        'type': cls.Type,
                        'class': cls,
                        }

                Plugins[name] = plugin_info

#print Plugins
#print Transdirs
if __name__ == '__main__':
    print Plugins
    print Transdirs

